

#include "app_net.h"

static pthread_t	bdcast_thread;


int32_t app_bdcast_task(void)
{
	int ret = 0;
	char send_buf[1024] = { 0 };
	char recv_buff[1024] = { 0 };

	log_n("udp bcast client\n");

	//1、创建一个套接字文件描述符
	int socketfd = socket(AF_INET,SOCK_DGRAM,0);
	if(socketfd == -1)
	{
		log_n("socket fail");
		return -1;
	}

	//2、将广播属性添加到套接字中
	int on = 1;
	setsockopt(socketfd,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on));

	struct timeval timeout = { 2,0 };

	ret = setsockopt(socketfd, SOL_SOCKET, SO_SNDTIMEO, (struct timeval*)&timeout, sizeof(struct timeval));
	if (ret < 0) {
		log_e("set socket timeout error,ret=%d\n", ret);
	}
	else {
		log_n("set succeed.\n");
	}

	ret = setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, (struct timeval*)&timeout, sizeof(struct timeval));
	if (ret < 0) {
		log_e("set socket timeout error,ret=%d\n", ret);
	}
	else {
		log_n("set succeed.\n");
	}

	struct sockaddr_in send_addr;
	send_addr.sin_family      = AF_INET;
    send_addr.sin_port        = htons(CFG_LISTEN_PORT);
    send_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);

	struct sockaddr_in recv_addr;
	int len = sizeof(struct sockaddr_in);

	log_n("app bdcast succeed.\n");

	while(1)
	{

		usleep(1000*1000);

		memset(send_buf,0,sizeof(send_buf));

		sprintf(send_buf,"%s","i am rk3568 client.");

		ret = sendto(socketfd,send_buf,strlen(send_buf),0,(struct sockaddr*)&send_addr,sizeof(struct sockaddr_in));
		//*******************************************************************************************************
	
		memset(recv_buff, 0, sizeof(recv_buff));
		ret = recvfrom(socketfd, recv_buff, sizeof(recv_buff), 0, (struct sockaddr*)&recv_addr, &len);
		if (ret >= 0) {
			log_i("recv:%s\n", recv_buff);
			//log_n("ip  :%s\n", inet_ntoa(recv_addr.sin_addr));
			//log_n("port:%d\n", ntohs(recv_addr.sin_port));
		}
		//*******************************************************************************************************
	}

	//4、关闭套接字
	close(socketfd);

	return 0;
}




int32_t app_bdcast_create(void)
{
	int ret = -1;
	
	ret=pthread_create(&bdcast_thread, NULL, app_bdcast_task, NULL);
	if(ret != 0){
		log_e("error=%s\n",strerror(ret));
	}



	return 0;
}



